<?php
namespace app\zhonghang\controller;
use think\Config;
use youwen\exwechat\api\accessToken;
use youwen\exwechat\api\OAuth\OAuth;
class Api{


    public function index(){ 
		
        if (isset($_GET['echostr'])) {   
            $echoStr = $_GET["echostr"];  
            $signature = $_GET["signature"];
            $timestamp = $_GET["timestamp"];
            $nonce = $_GET["nonce"];
            $token = 'naisimeiye';
            $tmpArr = array($token, $timestamp, $nonce);
            sort($tmpArr, SORT_STRING);
            $tmpStr = implode($tmpArr);
            $tmpStr = sha1($tmpStr);
            if($tmpStr == $signature){
            	ob_clean();
                echo $echoStr;
            }else{ 
                echo 'error';   
            }
			
        }else{
           $this->responseMsg();
        } 
    }
	public function request_post(){
		$appid = 'wx34786f0678e605ef';
		$appsec = 'c755161bc0c0c59dd48b3afe638eaabb';
		$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsec;

		$token = $this->getByUrl($url);
		dump($token);
		
		
// 		$url = $OAuth->getCodeUrl($redirect_uri, $scope, $state);
		
		
		$param = '';
		
		
		$token = 'naisimeiye';
		$postUrl = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$token;
		$curlPost = $param;
		$ch = curl_init();//初始化curl
		curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
		curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
		curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
		curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
		$data = curl_exec($ch);//运行curl
		curl_close($ch);
		dump($data);
		return $data;	
	}
	/**
	 * 请求方式：GET（HTTPS）
	 */
	public function getByUrl($url){
		$ch = curl_init();
		$timeout = 5;
		curl_setopt ($ch, CURLOPT_URL, $url);
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		$file_contents = curl_exec($ch);
		curl_close($ch);
		$return_array = json_decode($file_contents,true);
		return $return_array;
	
	}
	
	
    
    
    
    /**
     * 推送类型
     * event       推送事件
     * text         文本消息
     */
    public function responseMsg(){
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        dump($postStr);
        
        if (!empty($postStr)) {
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);
            
            switch ($RX_TYPE) {
                //推送事件
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                //推送文本消息
                case "text":
                    $result = $this->receiveText($postObj);
                    break; 
                default:
                    $result = "unknow msg type: " . $RX_TYPE;
                    break;
            }
			echo $result;
        } else {
            
            exit();
        }
    }
 
 /**
  * 处理微信推送事件
  * 事件类型
  * subscribe   关注事件
  * unsubscribe 取消关注
  * SCAN		         参数二维码已关注执行该事件
  * CLICK       点击自定义菜单
  */
 private function receiveEvent($object){
	 
     $content = "";
     switch ($object->Event) {
         case "subscribe":
        //$content .= (! empty($object->EventKey)) ? ("\n来自二维码场景 " . str_replace("qrscene_", "", $object->EventKey)) : "";
         $openid = $object->FromUserName;	
            $data = M("lbb_tuisong")->where(array("status"=>0))->select();
            $content = array();
            foreach($data as $val){
            $content[] = array("Title" =>$val['title'], 
                   "Description" =>'1', 
                   "PicUrl" =>"http://www.lvbaobiao.cn/".$val['pic'], 
                   "Url" =>$val['url'].'?'.$object->FromUserName);
              }
             return $this->gtransmitText($object,$content);
             break;
         case "unsubscribe":
             $content = "取消关注";
             break;
         case "SCAN":
             $content = "扫描场景 " . $object->EventKey;
             return $this->transmitText($object, $content);
             break;
         case "CLICK":
             switch ($object->EventKey) {
                 case "COMPANY":
                     $content = "方倍工作室提供互联网相关产品与服务。";
                     break;
                 default:
                     $content = "点击菜单：" . $object->EventKey;
                     break;
             }
             return $this->transmitText($object, $content);
             break;
         default:
             $content = "receive a new event: " . $object->Event;
             return $this->transmitText($object, $content);
             break;
     }
 }
//
//  /**
//   * 处理微信推送文本消息(图文回复)
//   * @param unknown $object
//   */
 private function receiveText($object) {
     $keyword = trim($object->Content);
     $res = M('lbb_tuisong')->where(array('title'=>['like','%'.$keyword.'%'],'status'=>0))->find();
     if($res){
        return $this->transmitNews($object, $res);
     }else{
        return $this->transmitText($object, '你好啊,我暂时还回答不上来哟');

    }
    
 }
//
     /**
      * 文本消息回复
      */
     private function transmitText($object, $message){
        $textTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <Content><![CDATA[%s]]></Content>
            <FuncFlag>0</FuncFlag>
            </xml>";
                    $contentStr = $message;

    $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(),'text', $message);
        return $result;
     
     }
     /**
      * 关注消息回复
      */
     private function gtransmitText($object, $newsArray){
                 if(!is_array($newsArray)){
            return;
        }
        $itemTpl = "    <item>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <PicUrl><![CDATA[%s]]></PicUrl>
        <Url><![CDATA[%s]]></Url>
    </item>
";
        $item_str = "";
        foreach ($newsArray as $item){
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
        }
        $xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str</Articles>
</xml>";
                $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
        return $result;
     
     }
     /**
      * 图文消息回复
      */
     private function transmitNews($object, $newsArray){
         $textTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <ArticleCount><![CDATA[%s]]></ArticleCount>
            <Articles>
                <item>
                    <Title><![CDATA[%s]]></Title> 
                    <Description><![CDATA[%s]]></Description>
                    <PicUrl><![CDATA[%s]]></PicUrl>
                    <Url><![CDATA[%s]]></Url>
                </item>                               
            </Articles>
            </xml>";  
         $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), 'news','1',$newsArray['title'],$newsArray['title'],'http://www.lvbaobiao.cn'.$newsArray['pic'],$newsArray['url']);
         return $result;
     }
}